package com.hkpickup.apple;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hkpickup.web.*;
/**
 * To monitor IPad3 status.
 * http://store.apple.com/hk/browse/home/shop_ipad/family/ipad/select_ipad
 * 20120313
 * @author hkpickup
 * 
 */
public class Ipad3MonitorServlet extends HttpServlet {
	
	static Ipad3SiteStatus ipadStatus = new Ipad3SiteStatus();
	static SmsAlert smsAlert = new SmsAlert();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HtmlFetcher f = new HtmlFetcher("http://store.apple.com/hk/browse/home/shop_ipad/family/ipad/select_ipad" );
		int respondCode = f.fetch();
		String smsContent = null;
		
		// Store website status 
		ipadStatus.updateTime();
		//java.util.Date now = new java.util.Date();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
	    sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
	    String nowStr = sdf.format(ipadStatus.lastUpdate.getTime());
		if (respondCode == 200){
			if (f.getHtml().indexOf("unavailable")==-1){
				// Open
				ipadStatus.isOpenCount ++;		    
			    smsContent = "IPad "+nowStr;
			}else {
				ipadStatus.isOpenCount = 0;
				smsAlert.setAccumulatedSent(0);
			}			
		}else {
			// http is not 200 
			smsContent = "IPad site may be changed "+nowStr;
		}
		
		// Decide to sending sms
		if (smsAlert.getAccumulatedSent()<3 && smsContent!=null){
			//smsAlert.sendMsg(smsContent);			
		}
		resp.getWriter().print("Update time: " + nowStr);
		resp.getWriter().print("\nIpad site is opend count = " + ipadStatus.isOpenCount);
		resp.getWriter().print("\nAlert count = " + smsAlert.getAccumulatedSent());
		
		if (smsAlert.getAccumulatedSent()==Integer.MAX_VALUE-1) smsAlert.setAccumulatedSent(0);
		if (ipadStatus.isOpenCount==Integer.MAX_VALUE-1) ipadStatus.isOpenCount=0;
	}
	
}
